package com.ruoyi.base.redis.phone;

import com.ruoyi.base.exception.SysException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.util.Optional;
import java.util.concurrent.TimeUnit;

/**
 * 登录redis
 *
 * @author lcf
 */
@Component
public class PhoneCodeRedis {
    @Autowired
    public StringRedisTemplate redisTemplate;
    /**
     * 验证码前缀
     */
    private String phoneCodePrefix = "phoneCode:";
    /**
     * 设置时间前缀
     */
    private String setTimePrefix = "phoneCodeTime:";
    /**
     * 过期时间单位
     */
    private TimeUnit timeUnit = TimeUnit.MINUTES;
    /**
     * 缓存时间5分钟
     */
    private int time = 5;
    /**
     * 短信重发间隔1分钟
     */
    private int retryTime = 1;

    /**
     * 删除缓存
     */
    public void del(String phone) {
        redisTemplate.delete(getPhoneCodeKey(phone));
        redisTemplate.delete(getTimeKey(phone));
    }

    /**
     * 缓存手机验证码
     */
    public void cache(String phone, String code) {
        redisTemplate.boundValueOps(getPhoneCodeKey(phone)).set(code, time, timeUnit);
        redisTemplate.boundValueOps(getTimeKey(phone)).set("", retryTime, timeUnit);
    }

    /**
     * 获取手机验证码
     */
    public String get(String phone) {
        return redisTemplate.boundValueOps(getPhoneCodeKey(phone)).get();
    }

    /**
     * 检查重发间隔是否过短
     */
    public void checkTimeBetween(String phone) {
        boolean hasKey = Optional.ofNullable(redisTemplate.hasKey(getTimeKey(phone))).orElse(false);
        if (hasKey) {
            throw new SysException("验证码获取过于频繁");
        }
    }

    /**
     * 获取验证码key
     */
    private String getPhoneCodeKey(String phone) {
        return phoneCodePrefix + phone;
    }

    /**
     * 获取设置时间key
     */
    private String getTimeKey(String phone) {
        return setTimePrefix + phone;
    }
}
